export class HashMap {
    #table = {}

    set(key, value) {
        if (key != null && value != null) {
            const position = this.hashCode(key)
            this.#table[position] = new valuePair(position, value)
            return true
        }
        return false
    }

    get(key) {
        if (key != null) {
            const position = this.hashCode(key)
            const valuePair = this.#table[position]
            return valuePair == null ? undefined : valuePair.value
        }
    }

    remove(key) {
        if (key != null) {
            const hashKey = this.hashCode(key)
            const valuePair = this.#table[hashKey]
            if(valuePair != null){
                delete this.#table[hashKey]
                return true
            }
            return false
        }
    }

    // 打散方法
    hashCode(key) {
        const tableKey = this.toStrFn(key)
        let hash = 5381
        for (let i = 0; i < tableKey.length; i++) {
            hash = (hash * 33) + tableKey.charCodeAt(i)
        }
        return hash % 1013
    }

    toStrFn(key) {
        if (key === null) {
            return 'NULL'
        } else if (key === undefined) {
            return 'UNDEFINED'
        } else if (typeof key === 'string' || key instanceof String) {
            return key
        }
        return JSON.stringify(key)
    }
}

class valuePair {
    constructor(key, value) {
        this.key = key
        this.value = value
    }
}